package kata14;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Trigram {

    private List<String> sourceWords;

    private Map<String,List<String>> wordDictionary;
    
    public Trigram(){
        sourceWords = new ArrayList<>();
        wordDictionary = new HashMap<>();
    }

    public void readFileWords(String path){
        try(BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(path)))){
            String strLine = "";
            List<String> splitList;
            while ((strLine = br.readLine()) != null){
                splitList = Stream.of(strLine.trim().split(" "))
                        .filter(word -> word != null && word.length() > 0)
                        .collect(Collectors.toList());
                sourceWords.addAll(splitList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void initWordDictionary(){
        int arraySize = sourceWords.size();
        if(arraySize >= 3){
            arraySize = arraySize -2;
            String key = null;
            List<String> mapInnerList;
            for(int i = 0; i < arraySize; i++){
                key = sourceWords.get(i).concat(" ").concat(sourceWords.get(i+1));
                mapInnerList = wordDictionary.get(key);
                if(mapInnerList == null){
                    mapInnerList = new ArrayList<>();
                }
                mapInnerList.add(sourceWords.get(i+2));
                wordDictionary.put(key,mapInnerList);
            }
        }
    }

    public List<String> getNextPossibleWords(String words){
        return wordDictionary.get(words);
    }

    public String genericWordLine(String words){
        if(wordDictionary.get(words) == null){
            throw new RuntimeException("单词库中不存在输入的单词");
        }
        List<String> resultList = Stream.of(words.split(" ")).collect(Collectors.toList());
        String nextWord;
        String middle;
        while (true){
            middle = resultList.get(resultList.size() - 2).concat(" ").concat(resultList.get(resultList.size() - 1));
            nextWord = getNextRandomWord(middle);
            if(nextWord == null){
                break;
            }
            resultList.add(nextWord);
        }
        return resultList.stream().collect(Collectors.joining(" "));
    }

    private String getNextRandomWord(String currentWords){
        List<String> innerWords = wordDictionary.get(currentWords);
        if(innerWords == null || innerWords.size() == 0){
            return null;
        }
        Random random = new Random();
        return innerWords.get(random.nextInt(innerWords.size()));
    }
}
